import React, { useState, useEffect, useMemo, useRef } from 'react';
import styles from './pushNotifications.less';
import { UnorderedListOutlined, TeamOutlined, HeartOutlined } from '@ant-design/icons';
import { getMessage, getFollowList } from '@/services/getPushNotifications';
import { notificationsItem, notiFollowListItem } from '@/common/notifications';
import { useScroll, useRequest } from '@umijs/hooks';

interface notificationsItemResult {
  list: notificationsItem[];
}

const NotificationsMenu: React.FC = props => {
  const [selectCurrent, setSlectCurrent] = useState<string>('message');

  const headerList = useRef([
    { svg: <UnorderedListOutlined />, title: 'message' },
    { svg: <TeamOutlined />, title: 'user' },
    { svg: <HeartOutlined />, title: 'heart' },
  ]);

  function getContent() {
    switch (selectCurrent) {
      case 'message':
        return <LoadMoreMessageList></LoadMoreMessageList>;
      case 'user':
        return <FollowList></FollowList>;
      case 'heart':
        return <LoadMoreMessageList></LoadMoreMessageList>;
      default:
        return <LoadMoreMessageList></LoadMoreMessageList>;
    }
  }

  return (
    <div className={styles['notifications-menu']}>
      <span className={styles['Popover-arrow']}></span>
      <div className={styles['PushNotifications-header']}>
        {headerList.current.map((value, index) => {
          return (
            <button
              key={index}
              className={`${styles['PushNotifications-tab']} button`}
              onClick={() => {
                setSlectCurrent(value.title);
              }}
            >
              <span
                className={
                  selectCurrent === value.title ? styles['PushNotifications-tab-active'] : ''
                }
              >
                {value.svg}
              </span>
            </button>
          );
        })}
      </div>
      {getContent()}
      <div className={styles['Notifications-footer']}>
        <a href="">设置</a>
        <a href="">查看全部通知</a>
      </div>
    </div>
  );
};

export default NotificationsMenu;

const LoadMoreMessageList = () => {
  const [listCount, setListCount] = useState<number>(0); // 用于记录获取的消息数目
  const [scroll, ref] = useScroll<HTMLDivElement>();
  const position = useRef<number>(0); // 用于记录scroll值

  // 初始化获取list数据 和 useRequsest loadMore配置
  const { data, loading, loadMore, loadingMore } = useRequest(
    (d: notificationsItemResult | undefined) => getMessage(),
    {
      loadMore: true,
      cacheKey: 'test',
      formatResult: res => {
        return {
          list: [res],
        };
      },
      onSuccess: data => {
        // 数据数量计数
        let count = 0;
        data.list.map(data => {
          data.data.map(value => {
            count++;
          });
        });
        setListCount(listCount + count);
      },
    },
  );

  // 滑动加载相关
  useEffect(() => {
    if (scroll.top > position.current && !loadingMore && scroll.top >= (listCount - 1) * 78 - 350) {
      loadMore();
    }
    position.current = scroll.top;
  }, [listCount, loadMore, loadingMore, scroll]);

  return (
    <div ref={ref} className={styles['PushNotifications-content']}>
      {data &&
        data.list.length > 0 &&
        data.list.map(item => {
          return item.data.map((value, index) => {
            return (
              <div key={index} className={styles['PushNotifications-item']}>
                <span>
                  <span className={styles['PushNotifications-actor']}>
                    {value.content.actors[0] ? (
                      <a href={value.content.actors[0].link}>{value.content.actors[0].name}</a>
                    ) : (
                      <a href={value.content.actors.link}>{value.content.actors.name}</a>
                    )}
                  </span>
                </span>
                {value.content.verb + ' '}
                <span>
                  <a href={value.content.target.link}>{value.content.target.text}</a>
                </span>
              </div>
            );
          });
        })}
      {loadingMore && <div>Loading......</div>}
    </div>
  );
};

interface notiFollowListResult {
  list: notiFollowListItem[];
}

const FollowList = () => {
  const [scroll, ref] = useScroll<HTMLDivElement>();

  const { data, loading, loadMore, loadingMore } = useRequest(
    (d: notiFollowListResult | undefined) => getFollowList(),
    {
      loadMore: true,
      cacheKey: 'followList',
      formatResult: res => {
        return {
          list: [res],
        };
      },
    },
  );
  return (
    <div ref={ref} className={styles['PushNotifications-content']}>
      <div className={styles['PushNotifications-followTitle']}>这些人最近关注了你</div>
      {data &&
        data.list.length > 0 &&
        data.list.map(item => {
          return item.data.map((value, index) => {
            return (
              <a
                className={`${styles['PushNotifications-item']} ${styles['PushNotifications-followItem']}`}
                href={value.content.target.link}
                key={index}
              >
                <div className={styles.AuthorInfo}>
                  <span>
                    <img
                      className={styles['follow-list-user-img']}
                      src={value.target.avatar_url}
                      alt=""
                    />
                  </span>
                  <div className={styles['AuthorInfo-content']}>{value.target.name}</div>
                </div>
              </a>
            );
          });
        })}
    </div>
  );
};
